package com.company.genealogy.web.controller;

import com.company.genealogy.common.result.ApiResponse;
import com.company.genealogy.web.entity.User;
import com.company.genealogy.web.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试控制器
 * 
 * 用于验证系统基本功能，包括数据库连接、用户查询等。
 * 
 * @author chenzhixiang
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/v1/test")
public class TestController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试数据库连接
     * 
     * @return 数据库连接状态
     */
    @GetMapping("/db-connection")
    public ApiResponse<String> testDbConnection() {
        try {
            // 尝试查询用户表
            List<User> users = userMapper.selectList(null);
            return ApiResponse.success("数据库连接正常，用户数量: " + users.size());
        } catch (Exception e) {
            return ApiResponse.fail("数据库连接失败: " + e.getMessage());
        }
    }

    /**
     * 测试用户查询
     * 
     * @return 用户列表
     */
    @GetMapping("/users")
    public ApiResponse<List<User>> testUserQuery() {
        try {
            List<User> users = userMapper.selectList(null);
            return ApiResponse.success(users);
        } catch (Exception e) {
            return ApiResponse.fail("用户查询失败: " + e.getMessage());
        }
    }

    /**
     * 测试系统状态
     * 
     * @return 系统状态信息
     */
    @GetMapping("/status")
    public ApiResponse<String> testSystemStatus() {
        return ApiResponse.success("系统运行正常");
    }

    /**
     * 测试认证状态
     * 
     * @return 认证状态信息
     */
    @GetMapping("/auth-status")
    public ApiResponse<Map<String, Object>> testAuthStatus() {
        Map<String, Object> result = new HashMap<>();
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        result.put("isAuthenticated", authentication != null && authentication.isAuthenticated());
        result.put("principal", authentication != null ? authentication.getPrincipal() : null);
        result.put("authorities", authentication != null ? authentication.getAuthorities() : null);
        result.put("name", authentication != null ? authentication.getName() : null);
        
        return ApiResponse.success(result);
    }
} 